sap.ui.define([
    "sap/m/bbf41/Module/controller/BaseController",
    "sap/ui/model/json/JSONModel"
], function (BaseController, JSONModel) {
    "use strict";
    var oJSONModel;
    return BaseController.extend("sap.m.bbf41.Module.controller.RTB2", {
        onInit: function () {
            oJSONModel = this.loadFoundryDataModel();
            var oView = this.getView();
            oView.setModel(oJSONModel);
            oView.byId('B38A').setHeaderSpan([2, 1]);
            oView.byId('B38B').setHeaderSpan([2, 1]);
            oView.byId('B48A').setHeaderSpan([2, 1]);
            oView.byId('B48B').setHeaderSpan([2, 1]);
        },
        handlePressOpenMenu: function (oEvent) {
            var oButton = oEvent.getSource();
            // create menu only once
            if (!this._menu) {
                this._menu = sap.ui.xmlfragment(
                    "sap.m.bbf41.Module.MenuItemEventing",
                    this
                );
                this.getView().addDependent(this._menu);
            }
            var eDock = sap.ui.core.Popup.Dock;
            this._menu.open(this._bKeyboard, oButton, eDock.BeginTop, eDock.BeginBottom, oButton);
        },
        handleRefresh: function () {
            oJSONModel = this.loadFoundryDataModel();
            var oView = this.getView();
            oView.setModel(oJSONModel);
        },
        loadFoundryDataModel: function () {
            var me = this,
                oModel = new JSONModel(),
                oView = this.getView(),
                oTable = oView.byId('table'),
                oMessageStrip = oView.byId('messageStrip');
            oTable.setBusy(true);
            oMessageStrip.setBusy(true);
            jQuery.ajax({
                url: '/NEP/ALS/api/rtb2',
                dataType: "json",
                success: function (resp) {
                    var oData = me.buildTableData(resp);
                    oModel.setData(oData);
                }.bind(this),
                error: function () {
                    jQuery.sap.log.error("failed to load json");
                },
                complete: function () {
                    oTable.setBusy(false);
                    oMessageStrip.setBusy(false);
                }
            });
            return oModel;
        },
        onNavButtonPress: function () {
            //window.history.back();
            window.location.href = '/m';
        },
        handleMenuItemPress: function (oEvent) {
            var routeName = oEvent.getSource().data('area');
            this.getRouter().navTo(routeName);
        },
        buildTableData: function (resp) {
            var data = {
                "ProductCollection": [
                    {
                        "Type": "Target",
                        "TotalWeek": 0,
                        "TotalToday": 0,
                        "B38AToday": 0,
                        "B38AWeek": 0,
                        "B38BToday": 0,
                        "B38BWeek": 0,
                        "B48AToday": 0,
                        "B48AWeek": 0,
                        "B48BToday": 0,
                        "B48BWeek": 0,
                        "rowNum": 0
                    },
                    {
                        "Type": "Current",
                        "TotalWeek": 0,
                        "TotalToday": 0,
                        "B38AToday": 0,
                        "B38AWeek": 0,
                        "B38BToday": 0,
                        "B38BWeek": 0,
                        "B48AToday": 0,
                        "B48AWeek": 0,
                        "B48BToday": 0,
                        "B48BWeek": 0,
                        "rowNum": 1
                    },
                    {
                        "Type": "Forecast",
                        "TotalWeek": 0,
                        "TotalToday": 0,
                        "B38AToday": 0,
                        "B38AWeek": 0,
                        "B38BToday": 0,
                        "B38BWeek": 0,
                        "B48AToday": 0,
                        "B48AWeek": 0,
                        "B48BToday": 0,
                        "B48BWeek": 0,
                        "rowNum": 2
                    },
                    {
                        "Type": "Planned",
                        "TotalWeek": 0,
                        "TotalToday": 0,
                        "B38AToday": 0,
                        "B38AWeek": 0,
                        "B38BToday": 0,
                        "B38BWeek": 0,
                        "B48AToday": 0,
                        "B48AWeek": 0,
                        "B48BToday": 0,
                        "B48BWeek": 0,
                        "rowNum": 3
                    },
                    {
                        "Type": "Deviation",
                        "TotalWeek": 0,
                        "TotalToday": 0,
                        "B38AToday": 0,
                        "B38AWeek": 0,
                        "B38BToday": 0,
                        "B38BWeek": 0,
                        "B48AToday": 0,
                        "B48AWeek": 0,
                        "B48BToday": 0,
                        "B48BWeek": 0,
                        "rowNum": 4
                    }
                ],
                "LineRate": "0"
            };
            var po = data.ProductCollection;

            if (resp && resp['rtb2_data']) {
                $.each(resp['rtb2_data'], function (i, o) {
                    var todayIdx = i + 'Today',
                        weekIdx = i + 'Week';
                    $.each(o, function (ii, oo) {
                        po[ii][todayIdx] = oo['today'];
                        po[ii][weekIdx] = oo['current_week'];
                        po[ii]['TotalToday'] += parseInt(oo['today']);
                        po[ii]['TotalWeek'] += parseInt(oo['current_week']);

                        po[ii]['_' + todayIdx] = todayIdx;
                        po[ii]['_' + weekIdx] = weekIdx;
                    });
                });

                this.calcLineRate(data);
            }
            return data;
        },
        calcLineRate: function (data) {
            var date = new Date(),
                y = date.getFullYear(),
                m = date.getMonth() + 1,
                d = date.getDate(),
                paddingNum = function (n) {
                    if (n < 10) {
                        n = '0' + n;
                    }
                    return n;
                };
            var ds = y + '/' + paddingNum(m) + '/' + paddingNum(d) + ' 06:00:00',
                ts = (new Date(ds)).getTime() / 1000,
                nts = parseInt((new Date()).getTime() / 1000),
                nh = parseInt((nts - ts) / 360) / 10,
                rate = nh != 0 ? parseInt(data['ProductCollection'][1]['TotalToday'] * 100 / nh) / 100 : 0;
            data['LineRate'] = rate + ' U/H';
        }
    });

});
